<template>
  <div class="h-100 pdf-box overflow-y" ref="pdfBox">
    <!-- <div class="page-tool">
      <div class="page-tool-item" @click="lastPage">上一页</div>
      <div class="page-tool-item" @click="nextPage">下一页</div>
      <div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
      <div class="page-tool-item" @click="pageZoomOut">放大</div>
      <div class="page-tool-item" @click="pageZoomIn">缩小</div>
    </div> -->
    <template v-for="pageNum in pageNums">
      <div v-if="rect.height" :key="pageNum" ref="pageRefs" class="h-100">
        <vue-pdf-embed v-if="pageVisibility[pageNum]" :source="doc" :page="pageNum" />
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onBeforeUnmount, onMounted, nextTick } from 'vue';
import { useRect } from '@vant/use';
import VuePdfEmbed, { useVuePdfEmbed } from 'vue-pdf-embed';
import pdf from './testpdf.pdf';

const { doc } = useVuePdfEmbed({
  source: pdf
});
const pageRefs = ref([]);
const pageVisibility = ref({});
let pageIntersectionObserver;
const pdfBox = ref();
const pageNums = computed(() => (doc.value ? [...Array(doc.value.numPages + 1).keys()].slice(1) : []));
const rect = ref({});

const resetPageIntersectionObserver = () => {
  pageIntersectionObserver?.disconnect();
  pageIntersectionObserver = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const index = pageRefs.value.indexOf(entry.target);
        const pageNum = pageNums.value[index];
        pageVisibility.value[pageNum] = true;
      }
    });
  });
  pageRefs.value.forEach(element => {
    pageIntersectionObserver.observe(element);
  });
};

watch(pageNums, newPageNums => {
  pageVisibility.value = { [newPageNums[0]]: true };
  nextTick(() => {
    resetPageIntersectionObserver();
  });
});

onBeforeUnmount(() => {
  pageIntersectionObserver?.disconnect();
});

onMounted(() => {
  rect.value = useRect(pdfBox);
  console.log(rect.value); // -> 元素的大小及其相对于视口的位置
});
// const handleDocument = pdf => {
//   if (pdf.numPages) {
//     pdfLoading.value = false;
//     state.numPages = pdf.numPages;
//   }
// };

// const lastPage = () => {
//   if (state.pageNum > 1) {
//     state.pageNum -= 1;
//   }
// };
// const nextPage = () => {
//   if (state.pageNum < state.numPages) {
//     state.pageNum += 1;
//   }
// };

// https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf
</script>

<style lang="scss" scoped></style>
